<template>
    <a-modal :title="title[step]"     
        :centered="true"
        :footer="null"
        :maskClosable="false"
        :width=900
        class="mag-svg-modal"
         v-model="show" @ok="handleOk">
            <a @click="mapBack" v-if="step === 2||step === 3" style="position: absolute;right: 55px;top:11px;font-size: 16px;color:#15837a;">返回</a>
            <div v-if="step === 0||step === 1">
                <svg version="1.1" type="system" x="780px" y="560px" viewBox="0 0 860 630" style="position: absolute; width: 780px; height: 560px;left:40px;top:60px">
                    <path @click="mapClick(mapChina,index)" @mouseenter="mapMouseenter(mapChina,index)" @mouseout="mapMouseout(mapChina,index)" v-for="(item, index) in mapChina" :key="index" stroke-linejoin='round' stroke-linecap='round' fill-rule='evenodd' :stroke="map.line_color" stroke-width='1' stroke-dasharray='none' :fill="item.bg" :d="item.pt.replace(/,/g, ' ').replace(/ e/g, '').replace(/L/g, 'L ').replace(/M/g, 'M ')" :txt="item.name" style='cursor: pointer;'/>
                </svg>
                <span @click="mapClick(mapChina,index)" @mouseenter="mapMouseenter(mapChina,index)" @mouseout="mapMouseout(mapChina,index)" v-for="(item, index) in mapChina" :key="index" class='wtm_a_txt' :txt="item.name" :style="'font-weight: bold;font-size:14px;color:#15837A;position:absolute;top:' + item.txt_pos[1] + 'px;left:' + item.txt_pos[0] + 'px;z-index:2;cursor: pointer;'">{{item.name.replace("省", "").replace("市", "").replace("地区", "").replace("区", "").replace("自治州", "")}}</span>
            </div>
            <div v-if="step === 2">
                <svg version="1.1" type="system" :x="city_x+'px'" :y="city_y+'px'" viewBox="0 0 860 630" :style="'position: absolute; width: '+city_x+'px; height: '+city_y+'px;left:'+city_left+'px;top:'+city_top+'px'">
                    <path @click="mapClick(mapChina[provinceIndex].city,index,'市辖区')" @mouseenter="mapMouseenter(mapChina[provinceIndex].city,index)" @mouseout="mapMouseout(mapChina[provinceIndex].city,index)" v-for="(item, index) in mapChina[provinceIndex].city" :key="index" stroke-linejoin='round' stroke-linecap='round' fill-rule='evenodd' :stroke="map.line_color" stroke-width='1' stroke-dasharray='none' :fill="item.bg" :d="item.point.replace(/,/g, ' ').replace(/ e/g, '').replace(/L/g, 'L ').replace(/M/g, 'M ').replace('$', '').replace('A', '').replace('D', '')" :txt="item.name" style='cursor: pointer;'/>
                </svg>
                <span v-if="item.txt_pos" @click="mapClick(mapChina[provinceIndex].city,index,'市辖区')" @mouseenter="mapMouseenter(mapChina[provinceIndex].city,index)" @mouseout="mapMouseout(mapChina[provinceIndex].city,index)" v-for="(item, index) in mapChina[provinceIndex].city" :key="index" class='wtm_a_txt' :txt="item.name" :style="'font-weight: bold;font-size:14px;color:#15837A;position:absolute;top:' + item.txt_pos[1] + 'px;left:' + item.txt_pos[0] + 'px;z-index:2;cursor: pointer;'">{{item.name&&item.name.replace("省", "").replace("市", "").replace("地区", "").replace("区", "").replace("自治州", "")}}</span>

                <div class="map-city-main">
                    <div class="map-city-list" v-for="(item, index) in mapChina[provinceIndex].city" :key="index">
                        <div class="map-city-name" >
                            <a @click="mapClick(mapChina[provinceIndex].city,index,'市辖区')" @mouseenter="mapMouseenter(mapChina[provinceIndex].city,index)" @mouseout="mapMouseout(mapChina[provinceIndex].city,index)" :txt="item.name">{{item.name}}</a>
                        </div>
                        <div class="map-city-area">
                            <a @click="mapClick(mapChina[provinceIndex].city,index,area)" @mouseenter="mapMouseenter(mapChina[provinceIndex].city,index)" @mouseout="mapMouseout(mapChina[provinceIndex].city,index)" v-for="(area, cindex) in item.area" :key="area.index">{{item.area[cindex]}}</a>
                        </div>
                    </div>
                    <div style="clear:both;"></div>
                </div>
            </div>
            <div v-if="step === 3" id="WTMap_Main" style="left: 0px;top: 44px;overflow: hidden;background-color: rgb(243, 241, 236);color: rgb(0, 0, 0);text-align: left;">
                <div id="allmap" ref="allmap"></div>
            </div>
        </a-modal>
</template>

<script>
    import { mapSvgData } from './../../utils/mapSvg'

    export default {
        // components: {
        // },
        data: () => ({
            map: {
                // data: mapSvgData,
                // china: [],
                width: [860, 860],
                height: [630, 630],
                line_color: "#B8BDC1",
                bg_color: "#9cd3e8",
                hover_color: "#ff9900",
                name_size: ["14px", "12px"],
                name_color: "#0222e3",
                name_hover_color: "#0222e3",
                max_level: 1,
                show_baidu: !1,
                show_baidu_level: 0,
                baidu_api_url: "http://api.map.baidu.com/getscript?v=2.0&ak=",
                baidu_key: "20480eb5ebe60b5b3c12178317758876",
                val_format: "p-c-a",
                keep_old: !0,
                placeholder: "请输入您要查找的城市",
                bdaddress_holder: "请输入您的详细地址",
                bdremark_holder: "例如：东明路御玺大厦A座12楼1201号",
                call_back: !1,
                show_remark: !0,
                readonly: !0,
                check_drag: !1
            },
            // 当前调用的名称
            name: '',
            // 标题
            title: ['','请选择省份','','地图'],
            // 省、市、地图 三层结构
            step: 1, // 0空 1省 2市 3地图
            maxStep: 3,
            // 省、市 数据处理好svg需要数据
            mapChina: [],
            // 当前选中的省Index
            provinceIndex: 0,
            // 当前选中的省
            province: "",
            // 当前选中的市Index
            cityIndex: "",
            // 当前选中的市
            city: "",
            city_x: 0,
            city_y: 0,
            city_top: 0,
            city_left: 0,
            // 当前选中的区
            area: "",
            // 地址
            address: "",
            // 门牌号
            addRemark: "",
            // 起始地的point
            point: {},
            show: false
        }),
        // props: {
        //     mapSvgVisible: {type: Boolean, default: false}
        // },
        mounted() {
        },
        computed: {
        },
        created: function () {
            for (var i = 0; i < mapSvgData.length; i++){
                var pt = mapSvgData[i].point,
                    city_pt = mapSvgData[i].city;
                pt = pt.replace(/,/g, " ").replace(/ e/g, "").replace(/L/g, "L ").replace(/M/g, "M ")
                for (var j = 0;j < mapSvgData[i].city.length; j++) {
                    var str = '';
                    var it = city_pt[j].point.replace(/ /g,',').split(","),
                    nt = 0,
                    tt = 0;
                    for (var k = 0;k <it.length;k++) {
                        // if(String(it[k]).indexOf("A")!=-1||String(it[k]).indexOf("D")!=-1) console.log('it[k]::',it[k])
                        if (it[k].indexOf('$')!=-1){
                            var vt = it[k].replace('L','').replace("$", "").replace("A", "").replace("D", "");
                            it[k] =  String(it[k]).indexOf("D")==-1 ? mapSvgData[i].sp[vt].pt : mapSvgData[i].sp[vt].pt.split("s").reverse().join(",");
                            // it[k] = mapSvgData[i].sp[vt].pt.split("s").reverse().join(",");
                            //console.log('it[k]:',it[k])
                            // if (mapSvgData[i].city[j].name =='阿勒泰地区'){
                            //     console.log('6666::',vt,mapSvgData[i].sp[vt].pt,it[k])
                            // }
                            // console.log('it[k]:',k,it[k])
                        }
                        str = str + (str!=''?',':'') + it[k];
                    }
                    if (str.length>0){
                        mapSvgData[i].city[j].point = str.replace(/,/g, " ").replace(/ e/g, "").replace(/s/g, " ").split("|")[0];
                        // if (mapSvgData[i].city[j].name =='阿勒泰地区'){
                        //     console.log('mapSvgData[i].city[j].point::',mapSvgData[i].city[j].point)
                        // }
                        // console.log('city[j].point:',k,mapSvgData[i].city[j].point)
                    }


                    // var wt = o.indexOf(",", o.indexOf("$")) != -1 ? o.indexOf(",", o.indexOf("$")) : o.indexOf(" e", o.indexOf("$")),
                    // rt = o.substring(o.indexOf("$"), wt), 
                    // vt = rt.replace("$", "").replace("A", "").replace("D", ""),
                    // st;
                    // st = r == 0 ? i[f].sp[vt].pt: at.sp[vt].pt;
                    // yt = rt.substring(rt.length - 1);
                    // o = yt == "A" ? o.replace(rt, st.replace(/s/g, ",")) : o.replace(rt, st.split("s").reverse().join(","))

                }

                this.mapChina.push({
                    name: mapSvgData[i].name,
                    bg: mapSvgData[i].bg,
                    pt: pt,
                    txt_pos: mapSvgData[i].txt_pos,
                    city: mapSvgData[i].city,
                    key: i,
                    size: mapSvgData[i].size
                })
            }
        },
        methods: {
            // 省点击
            mapClick (d,index,area){
                console.log('d,index,area:',this.step,d,index,area)
                if (this.step==1){
                    this.mapMouseout (d,index)
                    let _name = d[index].name
                    if ( _name== '钓鱼岛' || _name == '三沙市' ){
                        this.$message.warning(_name+'暂不可选择')
                        return;
                    }
                }
                // console.log('d,index,area:',this.step,d,index,area)
                if (d[index].city && d[index].city.length === 0) {
                    this.provinceIndex = index;
                    this.province = d[index].name;
                    this.city = '';
                    this.area = '';
                    this.backMapCont();
                    return;
                }
                if (this.step === 1){
                    this.provinceIndex = index;
                    this.province = d[index].name;
                    this.title[2] = this.province;
                    
                    if (d[index].size){
                        this.city_left = d[index].size[1];
                        this.city_top = d[index].size[2];
                        this.city_x = d[index].size[0], 
                        this.city_y = (630 * (this.city_x / 860)).toFixed(0);
                    }
                }else if (this.step === 2){
                    this.cityIndex = index;
                    this.city = d[index].name;
                    this.area = area;
                    this.title[2] = this.province;
                    
                    
                }
                // 如果当前已到最大层，关闭弹窗，返回选择的相应数据
                if (this.step === this.maxStep) {
                    if (this.maxStep === 2) {
                        this.getCityPoint();
                    }else{
                        this.backMapCont();
                    }
                    return;
                }
                this.step = this.step + 1;
                // console.log('this.maxStep === 3::',this.maxStep , this.step)
                if (this.maxStep === 3 && this.step === 3) {
                    setTimeout(()=>{
                        this.openMapSeat();
                    },10)
                    
                }
            },
            // 返回省市地图地址
            backMapCont () {
                let _city = this.cityFilter(this.province,this.city)
                let _area = this.areaFilter(this.province,this.city,this.area)
                this.$emit('change',{
                    name: this.name,
                    province: this.province,
                    city: _city,
                    area: _area,
                    provCityArea: this.province + (_city&&('-' +_city)) + (_area&&('-' + _area)),
                    address: this.address,
                    addRemark: this.addRemark,
                    point: this.point
                })
                this.show = false;
            },
            // 过滤北京、天津、上海、重庆 市为区的问题
            cityFilter(province,city){
                let _city = city
                switch(province){
                    case '北京市':
                    case '上海市':
                    case '天津市':
                    case '重庆市':
                        _city = province;
                        break;
                }
                return _city
            },
            // 过滤北京、天津、上海、重庆 市为区的问题
            areaFilter(province,city,area){
                let _area = area
                switch(province){
                    case '北京市':
                    case '上海市':
                    case '天津市':
                    case '重庆市':
                        if(city.indexOf('市')==-1) _area = city;
                        break;
                }
                return _area
            },
            // 打开百度地图
            openMapSeat () {
                    let obj = {
                        address: '',
                        addRemark: '',
                        lng: '',
                        lat: ''
                    }
                    var _this = this;
                    let map = new BMap.Map(_this.$refs.allmap); //弹出层的map

                    // map.disableDragging();
                    // 创建地理编码实例      
                    var myGeo = new BMap.Geocoder(); 
                    // 将地址解析结果显示在地图上，并调整地图视野
                    myGeo.getPoint(this.city, function(points){
                        if (points) {      
                            map.centerAndZoom(points, 16);      
                            // map.addOverlay(new BMap.Marker(point)); 
                            _this.point.lng = points.lng;
                            _this.point.lat = points.lat;
                            let point = new BMap.Point(points.lng,points.lat);
                            let marker = new BMap.Marker(point);
                            // map.disableDoubleClickZoom();
                            marker.enableDragging();
                            marker.addEventListener("dragend", function(e){
                                _this.point.lng = e.point.lng;
                                _this.point.lat = e.point.lat;
                                markerTem();
                            })
                            // map.centerAndZoom(this.city, 16);
                            map.addOverlay(marker);
                            markerTem(); 
                        }

                    }, this.city);
                    let opts = {
                        width: 350,     // 信息窗口宽度
                        height: 190,     // 信息窗口高度
                        enableAutoPan: true, //自动平移
                        title: '<p style="font-size:12px;color:#0048A2; font-weight:bold;border-bottom:#ddd 1px solid;padding-bottom:3px;"">'+ this.province +' - ' + this.city +' - '+ this.area +'</p>', // 信息窗口标题
                        enableMessage: true,//设置允许信息窗发送短息
                    }
                    let infoWindow = new BMap.InfoWindow('<div class="map-marker-main"><p><lable>详细地址：</lable><input class="ant-input" placeholder="请输入您的详细地址" id="mapAddress" type="text" value="" style="width:270px;" /></p><p><lable>门牌号：</lable><input placeholder="例如：荣之联大厦502号" id="mapAddRemark" style="width:270px;" class="ant-input" type="text" value="" /></p><p><button  style="display: block;width: 100px;margin: 0 auto;background: #15837a;color: #ffffff;"  class="ant-input" type="button" id="mapSubmit">确定</button></p><div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div></div>', opts);
                    // let infoWindow = new BMap.InfoWindow('<div id="mapFm"><nuxt-link>标题</nuxt-link></div>', opts)

                    // let fmc = new BMapInfoWindow();
                    // console.log('fmc::',fmc)
                    // document.getElementbyld('mapFm').appendChild(fmc.$el);
                        // let ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                        //     {"input" : "mapAddress"
                        //     ,"location" : map
                        //     ,onSearchComplete: function(e) {
                        //         console.log('11:',e)
                        //     }
                        // });
                        // ac.addEventListener("click", function(e) {  //鼠标放在下拉列表上的事件
                        //     console.log('fff:',e)
                        // });
                        // map.addEventListener("click", function(e){
                        //     console.log('aa:',e)
                        // });
                    // map.addEventListener("click", function(e){        
                    //     var pt = e.point;
                    //     myGeo.getLocation(pt, function(rs){
                    //         var addComp = rs.addressComponents;
                    //         console.log('map click rs::',JSON.stringify(pt),rs,e);
                    //     }); 
                    // })
                    function markerTem(){
                        var geoc = new BMap.Geocoder();
                        geoc.getLocation(new BMap.Point(_this.point.lng, _this.point.lat), function(rs){
                            document.getElementById('mapAddress').value = rs.address;
                            _this.mapAddress = rs.addressComponents;
                        }); 

                        map.openInfoWindow(infoWindow, new BMap.Point(_this.point.lng, _this.point.lat)); //开启信息窗口

                        document.getElementById('mapSubmit').onclick=function(){
                            let address = document.getElementById('mapAddress').value;
                            let addRemark = document.getElementById('mapAddRemark').value;
                            if (!address) return;
                            _this.address = address;
                            _this.addRemark = addRemark;
                            _this.backMapCont();
                        }

                        // // 百度地图API功能
                        // function G(id) {
                        //     return document.getElementById(id);
                        // }

                        // var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                        //     {"input" : "suggestId"
                        //     ,"location" : map
                        //     ,onSearchComplete: function(e) {
                        //         console.log('eee:',e)
                        //     }
                        // });
                        // ac.addEventListener("click", function(e) {  //鼠标放在下拉列表上的事件
                        //     console.log('fff')
                        // });
                        // ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
                        //     console.log('e:',e)
                        //     var str = "";
                        //     var _value = e.fromitem.value;
                        //     var value = "";
                        //     if (e.fromitem.index > -1) {
                        //         value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
                        //     }    
                        //     str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
                            
                        //     value = "";
                        //     if (e.toitem.index > -1) {
                        //         _value = e.toitem.value;
                        //         value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
                        //     }    
                        //     str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                        //     G("searchResultPanel").innerHTML = str;
                        // });

                        // var myValue;
                        // ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
                        //     console.log('ee',e)
                        //     var _value = e.item.value;
                        //     myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
                        //     G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
                            
                        //     setPlace();
                        // });

                        // function setPlace(){
                        //     map.clearOverlays();    //清除地图上所有覆盖物
                        //     function myFun(){
                        //         var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                        //         map.centerAndZoom(pp, 18);
                        //         map.addOverlay(new BMap.Marker(pp));    //添加标注
                        //     }
                        //     var local = new BMap.LocalSearch(map, { //智能搜索
                        //       onSearchComplete: myFun
                        //     });
                        //     local.search(myValue);
                        // }
                    }
            },
            // 省移入事件
            mapMouseenter (d,index){
                if (d[index]) d[index].bg = this.map.hover_color;
            },
            // 省移出事件
            mapMouseout (d,index){
                if (d[index]) d[index].bg = mapSvgData[index].bg;
            },
            // 返回上一层
            mapBack () {
                this.step = this.step - 1;
            },
            // handleCancel () {
            //   this.$emit('close')
            // },
            handleOk (d) {
                this.$emit('change')
            },
            // 通过省查询当前的key
            provinceKey () {
                for (var i = 0; i < this.mapChina.length; i++ ) {
                    if (this.mapChina[i].name == this.province) {
                        this.provinceIndex = this.mapChina[i].key;
                        return this.mapChina[i].key;
                    }
                }
            },
            // 通过省、市查询当前市的key
            cityKey () {
                const cityObj = this.mapChina[this.provinceIndex].city;
                for (var i = 0; i < cityObj.length; i++ ) {
                    if (cityObj[i].name == this.city) {
                        return i;
                    }
                }
            },
            /*
                name 名称，调用和返回区分
                visible bool 是否显示
                maxStep 选择显示最大到第几层
                province 省
                city 市
                area 县
            */
            mapSvgVisible (name,maxStep,province,city,area) {
                // console.log('mapSvgVisible::',name,maxStep,province,city,area)
                this.show = true;
                this.name = name;
                this.point = {};
                this.province = province;
                this.city = city;
                this.area = area;
                this.maxStep = maxStep;
                if (province !== '' && city !== '' && area !== '') {
                    this.step = 2;
                    const province = this.mapChina[this.provinceKey()];
                    this.mapClick (province.city,this.cityKey(),area);
                    if (province.size){
                        this.city_left = province.size[1];
                        this.city_top = province.size[2];
                        this.city_x = province.size[0], 
                        this.city_y = (630 * (this.city_x / 860)).toFixed(0);
                    }
                }else{
                    this.address = '';
                    this.step = 1;
                    // this.mapClick (this.mapChina,this.provinceKey())
                }
                
            },
            // 计算两地的距离
            distanceCount (start,end) {
                    let map = new BMap.Map(this.$refs.allmap);
                    var pointA = new BMap.Point(start.lng,start.lat);  // 创建点坐标A--大渡口区
                    var pointB = new BMap.Point(end.lng,end.lat);  // 创建点坐标B--江北区
                    this.$emit('distance',(map.getDistance(pointA,pointB)/1000).toFixed(2));
            },
            // 计算当前城市的经位度
            getCityPoint () {
                var _this = this;
                // 创建地理编码实例      
                var myGeo = new BMap.Geocoder(); 
                // 将地址解析结果显示在地图上，并调整地图视野    
                myGeo.getPoint(this.city, function(points){     
                    if (points) {
                        _this.point.lng = points.lng;
                        _this.point.lat = points.lat;
                        _this.backMapCont();
                    }
                }, this.city);
            }
        }
    }
</script>
<style>
    .mag-svg-modal #allmap{
        height:580px;
    }
    .mag-svg-modal .ant-modal-body{
        padding: 0px;
    }
    .mag-svg-modal .ant-modal-content{
        height: 640px;
    }
    .mag-svg-modal .map-city-main{
        width: 440px;font-size: 12px;position: absolute;right: 0;line-height: 26px;overflow-y: auto;height: 565px;text-align: left;
    }
    .mag-svg-modal .map-city-list{
        background:#F8F8F8;width: 100%;float: left;
    }
    .mag-svg-modal .map-city-name{
        white-space: nowrap;
        float: left;
    }
    .mag-svg-modal .map-city-name a{
        cursor: pointer;
        font-size: 14px;
        color: #ff6600;
        font-weight: bold;
        margin-right: 10px;
        margin-left: 5px;
    }
    .mag-svg-modal .map-city-area{
        float: left; 
        width: 350px;
    }
    .mag-svg-modal .map-city-area a{
            text-decoration: underline;
            cursor: pointer;
            font-family: 宋体;
            font-size: 12px;
            color: #15837a;
            display: inline-block;
            padding: 0 3px;
    }
    .mag-svg-modal .map-city-area a:hover{
            color: #15837a;
            background: #ff6600;
    }
    .mag-svg-modal .map-marker-main{
        margin-left: 5px;
    }
    .mag-svg-modal .map-marker-main lable{
            width: 72px;
            display: inline-block;
            text-align: right;
    }
</style>
